import { Contract } from '@ide/types/contract';
import { TreeItem, TreeItemPartial } from '@ide/types/tree';
import { formatTree, getContractNameByPath } from '@ide/utils/tools';
import { StateCreator } from 'zustand';
import { AppStore } from '.';
import { contractHasBuild, contractNames, deployContractList, getContractFiles, goModuleFiles, hasDeployContractList } from '@/api';
import { DeployContractListResponse } from '@ide/types/ideServer';

/**
 * 存储合约信息
 */
interface ContractData {
  hasBuild?: boolean;
  // contract: Contract;
  contracts:Contract[];
  compileContracts:DeployContractListResponse[];
  deployContracts:Contract[];
  // action?: number;
  refreshFiles: boolean;
  // file暂存了fileTree数据，后面和fileTree同步
  files: TreeItem[];
  modelFiles: TreeItem[];
  fileTree: TreeItem[];
  userId: string | number;
  chainmakerVersion: string;
  isPluginReady: boolean;
  activeTreeNode?: TreeItemPartial;
  debugContractName: string;
}

const initDate = {
  hasBuild: false,
  // contract: {},
  contracts: [],
  compileContracts:[],
  deployContracts:[],
  refreshFiles: false,
  files: [],
  modelFiles: [],
  fileTree: [],
  userId: '',
  chainmakerVersion: '',
  isPluginReady: false,
  activeTreeNode: undefined,
  debugContractName: '',
};
function getTotalTree(files: TreeItem[], modelFiles: TreeItem[]) {
  const tree = files?.slice();
  const lib = tree?.find((item) => (item.name === 'External Libraries'));
  if (lib?.children && modelFiles?.[0]) {
    lib.id = 'lib';
    lib.children[1] = modelFiles[0];
  }
  return tree;
}
export type ContractDataStore = ContractData & {
  setHasBuild: (type?: boolean) => void;
  // setContract: (contract: ContractData['contract']) => void;
  getHasBuild: (param: string[]) => void;
  getContracts: () => void; 
  getCompileContracts: () => void;
  getDeployContracts: () => void;
  getFiles: () => Promise<any>;
  getGoModuleFiles: (path:string) => void;
  setUserId: (id: string | number) => void;
  setChainmakerVersion: (version: string) => void;
  setIsPluginReady: (isReady?: boolean) => void;
  setActiveTreeNode: (item: TreeItemPartial) => void;
  setDebugContractName: (name: string) => void;
};

export const contractStore: StateCreator<ContractDataStore> = (set, get) => ({
  ...initDate,
  setHasBuild: (type) => set((state) => ({
    ...state,
    hasBuild: type
  })),
  // setContract: (contract) => set((state) => ({
  //   ...state,
  //   contract
  // })),
  getHasBuild: async (param: string[]) => {
    if (!param) {
      return;
    }
    // const res = await stat.server?.getContractHasBuild?.(param);
    const res = await contractHasBuild({ contractNames: param });
    if (res.code === 0 && typeof res.data.hasBuild === 'boolean') {
      set({
        hasBuild: res.data.hasBuild
      });
    }
  },
  getFiles: async () => {
    const stat = get() as AppStore;
    const res = await getContractFiles({ contractName: '' });
    if (res.code === 0 && res.data) {
      const contractFiles = formatTree(res.data.children);
      const obj: any = { files: contractFiles };
      if (stat.modelFiles) {
        obj.fileTree = getTotalTree(contractFiles, get().modelFiles);
      }

      // if (contractFiles[0]?.children?.[0]?.id && stat.contract.path !== contractFiles[0]?.children?.[0]?.path) {
      //   const newContract = {
      //     ...stat.contract,
      //     path: contractFiles[0]?.children?.[0].path
      //   };
      //   if (contractFiles[0].name) {
      //     newContract.contractName = contractFiles[0].children[0].name;
      //   }
      //   obj.contract = newContract;
      // }
      // console.log(obj);
      set(obj);
    }
  },
  getGoModuleFiles: async (contractName?:string) => {
    if (contractName) {
      const res = await goModuleFiles({ contractName });
      if (res.code === 0 && res.data) {
        const modelFiles = formatTree([res.data]);
        const obj: any = { modelFiles };
        const files = get().files;
        if (files) {
          // 利用get()获取最新files
          obj.fileTree = getTotalTree(files, modelFiles);
        }
        // console.log(obj);
        set(obj);
      }
    }
  },
  setUserId: (id) => set(() => ({
    userId: id
  })),
  getContracts: async () => {
    // const res = await stat.server?.getContractNames?.();
    const { code, data } = await contractNames({});
    if (code === 0 && data?.length !== 0) {
      const res = data.map((item:any) => ({
        path: item.path,
        contractName: item.name
      }));
      if (res) {
        const obj: any = { contracts: res };
        set(obj);
      }
    }
  },
  getCompileContracts: async () => {
    // const res = await stat.server?.getContractNames?.();
    const { code, data } = await deployContractList({});
    if (code === 0 && data.deployList?.length !== 0) {
      const obj: any = { compileContracts: data.deployList||[] };
      set(obj);
    }
  },
  getDeployContracts: async () => {
    // const res = await stat.server?.getContractNames?.();
    const { code, data } = await hasDeployContractList({});
    if (code===0&&data?.hasDeployList?.length) {
        // const obj: any = { deployContracts: data.hasDeployList||[] };
      set({ deployContracts: data.hasDeployList||[] });
    }else{
      set({deployContracts:[]})
    }
  },
  setChainmakerVersion: (version) => set(() => ({
    chainmakerVersion: version
  })),
  setIsPluginReady: (isPluginReady?: boolean) => set(() => ({
    isPluginReady
  })),

  setActiveTreeNode: (item) => set(() => ({ activeTreeNode: item })),
  setDebugContractName: (name) => set(() => ({ debugContractName: name })),
});
